<!-- 站点编辑弹窗 -->
<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :visible="visible" title="关联产品" width="750px" @update:visible="updateVisible">
    <el-form ref="form" :model="form" label-width="82px">
      <el-form-item label="产品：">

        <el-autocomplete v-model="code_name" :fetch-suggestions="querySearchProduct" placeholder="请搜索产品" value-key="name" @select="handleSelectProduct">
          <template slot-scope="{ item }">
            <div style="color: #333;"><b>{{ item.name }}</b></div>
            <div class="name" style="margin-top: -4px; display: flex;">
              型号: <span style="margin-right: 14px;">{{ item.model ? item.model : '无' }}</span>
              编号: <span style="margin-right: 14px;">{{ item.product_number ? item.product_number : '无' }}</span>
            </div>
          </template>
        </el-autocomplete>

      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>

export default {
  name: 'CodeEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 提交状态
      loading: false,
      code_name: ""
    };
  },
  watch: {
    data() {
      this.loading = false;
      this.form = Object.assign({}, this.data);
      this.code_name = this.data.product ? this.data.product.name : "";
    }
  },
  methods: {
    /* 编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$emit("editCode", this.form, this.form.id);
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    cancel() {
      this.updateVisible(false);
      this.category_name = "";
      this.form = {};
    },
    querySearchProduct(query, cb) {
      this.$http.get(`products?limit=10&name=${query}`,).then((res) => {
        cb(res.data.data.filter((item) => {
          return (!item.qrcode)
        }));
      });
    },
    handleSelectProduct(item) {
      this.form.product_id = item.id;
    },
  }
}
</script>

<style scoped>
.el-autocomplete {
  width: 100%;
}
</style>
